package com.example.learn_250821.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);

        System.out.println(lineCaptcha.getCode());
        String code = lineCaptcha.getCode();
        session.setAttribute("CAPTCHA_KEY", code);
        try {
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @RequestMapping("/check")
    public Boolean checkCaptcha(String captcha, HttpSession session) {
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }
        String code = (String) session.getAttribute("CAPTCHA_KEY");
        return captcha.equals(code);
    }
}
